package com.example.a10928.weifriend.ui.personal_center

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Handler
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.widget.Toast
import com.example.a10928.weifriend.App
import com.example.a10928.weifriend.R
import com.example.a10928.weifriend.http.api.VariableName
import com.example.a10928.weifriend.ui.BaseActivity
import com.example.a10928.weifriend.util.L
import com.example.a10928.weifriend.util.RxUtil
import com.example.a10928.weifriend.util.StatusBarUtil
import com.githang.statusbar.StatusBarCompat
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.mylhyl.circledialog.CircleDialog
import com.squareup.picasso.Picasso
import com.yanzhenjie.permission.*
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_personal_info.*
import okhttp3.Handshake
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

class PersonalInfoActivity : BaseActivity() {


    var provinceid:String?=""
    var cityid:String?=""
    val items = arrayOf("拍照", "从相册选择")

    var state:Boolean=false
    var img: LocalMedia?=null

    override fun getContentView(): Int {
        return R.layout.activity_personal_info
    }

    override fun initView() {
        StatusBarCompat.setStatusBarColor(this, Color.WHITE,true)
       supportActionBar?.hide()


        rl_province.setOnClickListener{

            var intent= Intent(this,SelectActivity::class.java)
            intent.putExtra(VariableName.TYPE,VariableName.PROVINCE)
            startActivityForResult(intent,VariableName.REQUEST_PROVINCE)
        }

        rl_city.setOnClickListener {
            if(!TextUtils.isEmpty(provinceid)){
                var intent= Intent(this,SelectActivity::class.java)
                intent.putExtra(VariableName.TYPE,VariableName.CITY)
                intent.putExtra(VariableName.DATA,provinceid)

                startActivityForResult(intent,VariableName.REQUEST_CITY)
            }else{
                L.t("请先选择省份")
            }

        }

        ll_header.setOnClickListener {
            CircleDialog.Builder()
                    .setCanceledOnTouchOutside(false)
                    .setCancelable(false)
                    .setTitle("更换头像")
                    .setText("您是否需要更换头像")
                    .setNegative("取消", null)
                    .setPositive("确认"

                    ) { v ->
                        PictureSelector.create(this)
                                .openGallery(PictureMimeType.ofImage())
                                .maxSelectNum(1)
                                .minSelectNum(1)
                                .selectionMode(PictureConfig.SINGLE)
                                .previewImage(true)
                                .compress(true)
                                .forResult(VariableName.REQUEST_SELECT_IMG)
                    }
                    .show(supportFragmentManager)
        }

        tv_confirm.setOnClickListener {
            img?.compressPath
            if(img==null){
                L.t("请选择头像图片")
                return@setOnClickListener
            }
            if(TextUtils.isEmpty(et_name.text.toString())){
                L.t("请输入昵称")
                return@setOnClickListener
            }
            if(TextUtils.isEmpty(et_real_name.text.toString())){
                L.t("请输入真实姓名")
                return@setOnClickListener
            }
            if(TextUtils.isEmpty(et_phone.text.toString())){
                L.t("请输入手机号")
                return@setOnClickListener
            }
            if(TextUtils.isEmpty(provinceid)){
                L.t("请选择省份")
                return@setOnClickListener
            }
            if(TextUtils.isEmpty(cityid)){
                L.t("请输入城市")
                return@setOnClickListener
            }
            if(TextUtils.isEmpty(et_detail_address.text.toString())){
                L.t("请输入详细地址")
                return@setOnClickListener
            }

            CircleDialog.Builder()
                    .setCanceledOnTouchOutside(false)
                    .setCancelable(false)
                    .setTitle("确认提交")
                    .setText("确认提交个人资料")
                    .setNegative("取消", null)
                    .setPositive("确定") { v ->
                        var file= File(img?.compressPath)
                        val requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
                        val body = MultipartBody.Part.createFormData("head_img", file.getName(), requestBody)

                        App.app().bpService.changeUserMsg(
                                toRequestBody(App.app().user.userId) ,
                                toRequestBody(et_name.text.toString()) ,
                                toRequestBody(et_real_name.text.toString()),
                                toRequestBody(cityid!!),
                                toRequestBody(et_detail_address.text.toString()),
                                body)
                                .compose(RxUtil.io2mainLoad(this))
                                .subscribe(
                                        Consumer {
                                            L.t("修改成功")
                                            Handler().postDelayed(Runnable {
                                                finish()
                                            },500)
                                        },
                                        Consumer {
                                            RxUtil.errorException(it)
                                        }
                                )
                     }
                    .configNegative { params ->  params.textColor= Color.RED }
                    .show(getSupportFragmentManager())



        }


        App.app().bpService.getUserMsg(App.app().user.userId)
                .compose(RxUtil.io2mainLoad(this))
                .subscribe(
                        Consumer {

                            if(TextUtils.isEmpty(it.data.user_msg.address_detail)){
                                et_phone.setText(it.data.user_msg.user_phone)
                            }else{
                                Picasso.with(this).load(it.data.user_msg.user_headimg).into(iv_header)
                                state=true


                                et_name.setText(it.data.user_msg.user_name)
                                et_real_name.setText(it.data.user_msg.real_name)
                                et_phone.setText(it.data.user_msg.user_phone)
                                tv_province.setText(it.data.user_msg.province)
                                tv_city.setText(it.data.user_msg.city)
                                et_detail_address.setText(it.data.user_msg.address_detail)

                            }




                        },
                        Consumer {
                            RxUtil.errorException(it)
                        }
                )

    }


    fun toRequestBody(value: String): RequestBody {
        return RequestBody.create(MediaType.parse("text/plain"), value)
    }

    override fun initData() {
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)


        if(resultCode!= Activity.RESULT_OK){
            return
        }

        when(requestCode){
            VariableName.REQUEST_PROVINCE->{
                tv_province.setText(data?.getStringExtra(VariableName.NAME))
                provinceid=data?.getStringExtra(VariableName.ID)

            }

            VariableName.REQUEST_CITY->{
                tv_city.setText(data?.getStringExtra(VariableName.NAME))
                cityid=data?.getStringExtra(VariableName.ID)
            }
            VariableName.REQUEST_PERMISSION->{
                L.t("请到设置界面开启权限")
            }

            VariableName.REQUEST_SELECT_IMG->{
                val selectList = PictureSelector.obtainMultipleResult(data)
                if(selectList != null && selectList.size == 1 && selectList[0] != null){
                    img=selectList[0]

                    var bitmap=BitmapFactory.decodeFile(img?.compressPath)
                    iv_header.setImageBitmap(bitmap)
                }
            }


        }



    }


    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        //权限申请
        AndPermission.with(this)
                .requestCode(VariableName.REQUEST_PERMISSION)
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .callback(perm)
                .rationale { requestCode, rationale -> AndPermission.rationaleDialog(this@PersonalInfoActivity, rationale).show() }.start()
    }


    var perm:PermissionListener= object :PermissionListener{
        override fun onFailed(requestCode: Int, deniedPermissions: MutableList<String>) {
            Toast.makeText(this@PersonalInfoActivity, "权限申请失败", Toast.LENGTH_SHORT).show()
            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(this@PersonalInfoActivity, deniedPermissions)) {
                AndPermission.defaultSettingDialog(this@PersonalInfoActivity, VariableName.REQUEST_SETTING)
                        .setTitle("权限申请")
                        .setMessage("需要此权限")
                        .setPositiveButton("好")
                        .setNegativeButton("否", null)
                        .show()

            }
        }

        override fun onSucceed(requestCode: Int, grantPermissions: MutableList<String>) {

        }


    }



}
